package com.jzwl.common.upload;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import net.coobird.thumbnailator.Thumbnails;

import org.nutz.img.Images;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片裁剪
 */
public class ImageUtil {

	/**
	 * 生成缩略图
	 * @param img 原始图片（CMYK模式或者正常的jpg）
	 * @param width 要生成的缩略图的宽
	 * @param height 要生成的缩略图的高
	 * @throws IOException
	 */
	public static File imageThumbnail(MultipartFile img, int width, int height, File targetFile) throws IOException {
		//用org.nutz.img.Images进行处理
		BufferedImage bufferedImage = Images.read(img.getInputStream());
		int imageWidth = bufferedImage.getWidth();
		int imageHeitht = bufferedImage.getHeight();
		if (width > 0 && height > 0) {
			if (imageWidth > width && imageHeitht > height) {
				//裁剪
				Thumbnails.of(bufferedImage).size(width, height).keepAspectRatio(true).toFile(targetFile);
			} else if (imageWidth <= width && imageHeitht <= height) {
				//原图
				Thumbnails.of(bufferedImage).size(imageWidth, imageHeitht).keepAspectRatio(true).toFile(targetFile);
			} else if (imageWidth > width && imageHeitht <= height) {
				//只裁剪宽
				Thumbnails.of(bufferedImage).width(width).keepAspectRatio(true).toFile(targetFile);
			} else if (imageWidth <= width && imageHeitht > height) {
				//只裁剪高
				Thumbnails.of(bufferedImage).height(height).keepAspectRatio(true).toFile(targetFile);
			}
		}
		bufferedImage.flush();
		return targetFile;
	}
}
